package com.csy.client_server.client_side;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

//客户端向服务器端发送信息的线程
public class ClientSendServer implements Runnable
{
    private Socket socket;
    private StringBuffer name;
    private StringBuffer text;

    public ClientSendServer(Socket socket, StringBuffer name)
    {
        PrintStream printStream = null;
        try {
            printStream = new PrintStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        printStream.println("userName:" + name);
        this.socket = socket;
        this.name = name;
    }

    @Override
    public void run()
    {
        try
        {
            //获取服务器端的输出流
            PrintStream printStream = new PrintStream(socket.getOutputStream());
            while (true)
            {
                if(text==null)
                    continue;
                String msg = new String(text);
                if (msg.equals("exit"))
                {
                    printStream.println(msg);
                    printStream.close();
                    break;
                }
                else
                {
                    printStream.println(msg);
                    this.text=null;
                }
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void read(StringBuffer text)
    {
        this.text = text;
    }

    public void print()
    {
        System.out.println(this.text);
    }

    public void exit()
    {
        //获取服务器端的输出流
        PrintStream printStream = null;
        try
        {
            printStream = new PrintStream(socket.getOutputStream());
            //从键盘中输入信息
            while (true)
            {
                String msg = new String(text);
                if (msg.equals("exit"))
                {
                    printStream.println("exit");
                    printStream.close();
                    break;
                }
                else
                {
                    printStream.println(msg);
                    msg=null;
//                    this.text.setLength(0);
                }
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
